﻿using Abp.Application.Services;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using AVIS.OutBound.SMS.Dto;
using AVIS.OutBound.WizardAgent.Helpers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.SMS
{
    /// <summary>
    ///  短信服务
    /// </summary>
    public class SMSAppService : OutBoundAppServiceBase, ISMSAppService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public SMSAppService()
        {
          
        }
        /// <summary>
        ///  获取传入手机号注册时的验证码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public SMSOutput GetVerificationCode(SMSInput input)
        {
            //判断当前用户是否注册过
            //throw new UserFriendlyException("您的手机号已注册，请直接登陆");

            //生成6位随机码写入短信
            String code = GetRamdonCode();

            RedisHelper.StringSet(KeyPrefix + input.PhoneNumber, code, new TimeSpan(0, KeyExpireTime, 0));

            String product = ConfigurationManager.AppSettings["SMS_Product"] ?? string.Empty;//短信API产品名称
            String domain = ConfigurationManager.AppSettings["SMS_Domain"] ?? string.Empty; ;//短信API产品域名
            String accessKeyId = ConfigurationManager.AppSettings["SMS_AcessKeyId"] ?? string.Empty;
            String accessKeySecret = ConfigurationManager.AppSettings["SMS_AccessKeySecret"] ?? string.Empty;

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
  
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = input.PhoneNumber;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "刘旭";
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = "SMS_132970148";
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = "{\"code\":\""+ code + "\"}";
            
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                //返回验证码
                //OK 表示成功
                return new SMSOutput { Message = sendSmsResponse.Message };


            }
            catch (ServerException e)
            {
                Logger.Info($"SMS 发送错误（{e.ErrorMessage}）");
                return null;
            }
            catch (ClientException e)
            {
                Logger.Info($"SMS客户端错误（{e.ErrorMessage}）");
                return null;
            }
        }

        #region Private
        private const String KeyPrefix = "SMS_";
        private const int KeyExpireTime = 5;
        
        /// <summary>
        /// 获取随机6位字符
        /// </summary>
        /// <returns></returns>
        private String GetRamdonCode()
        {
            Random generator = new Random();
            String code = generator.Next(0, 999999).ToString("D6");
            return code;
        }
        #endregion
    }
}
